﻿namespace EAL.Database
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using EAL.Models;

    /// <summary>
    /// specialized list containing customers ; implements property change logic of an item in the list
    /// </summary>
    public class CustomerList : ObservableCollection<Customer>
    {
        private readonly DbContext _context;


        /// <summary>
        /// ctor receiving a list of customers as data source and the data context the customer list
        /// was retrieved from
        /// </summary>
        /// <param name="customers">list of customers used as data source</param>
        /// <param name="context">data context the customer list was retrieved from</param>
        public CustomerList(IEnumerable<Customer> customers, DbContext context)
            : base(customers)
        {
            this._context = context;

            //subscribe to property changed event of each customer in the list
            foreach (Customer item in customers)
                item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(item_PropertyChanged);
        }


        /// <summary>
        /// overridden insert method to add a new customer to the list and the underlying data context
        /// </summary>
        /// <param name="index">index to insert the item into the list</param>
        /// <param name="item">item to insert</param>
        protected override void InsertItem(int index, Customer item)
        {
            //add item to data context, too
            this._context.Customers.Add(item);

            //add item to itself
            base.InsertItem(index, item);

            //subcribe to property changed event of the newly added item
            item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(item_PropertyChanged);
        }

        /// <summary>
        /// removes an item from the collection and the data context
        /// </summary>
        /// <param name="index">index of the item to remove</param>
        protected override void RemoveItem(int index)
        {
            //remove item from context, ...
            this._context.Customers.Remove(this.Items[index]);

            //... unsubscribe from property changed event of that item ...
            this.Items[index].PropertyChanged -= item_PropertyChanged;

            //... and remove it from collection itself, too
            base.RemoveItem(index);
        }

        /// <summary>
        /// called when a property of a containing customer was changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void item_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            //call simply base method
            //(the logic exists already, but have to be called manually)
            this.OnPropertyChanged(e);
        }
    }
}
